<template>
  <div class="retrieve-form-wrapper">
    <div class="retrieve-form-title">重置密码</div>
    <!--<div class="retrieve-form-sub-title">{{ $t('login.form.title') }}</div>-->
    <div class="retrieve-form-error-msg">{{ errorMessage }}</div>
    <!-- 逻辑是这样的
          先选择是密保找回还是手机号找回 这时候需要两个按钮
     -->
    <div v-if="choiceVisible == true">
      <a-button type="primary" @click="securityQuestionButton">
        密保找回
      </a-button>
      <a-button type="primary" style="margin-left: 20px" @click="phoneButton">
        手机号找回
      </a-button>
    </div>
    <!-- 这里是密保找回的输入框 -->
    <div v-if="securityQuestionVisible == true">
      <a-form :model="toBackInfo">
        <!-- 第一步是先告诉后端我是谁，只传一个 -->
        <a-form-item label="用户名">
          <a-input
            v-model="toBackInfo.username"
            :placeholder="请输入用户名"
          ></a-input>
        </a-form-item>
        <a-form-item v-if="usernameButtonVisible == true">
          <a-button type="primary" @click="obtainSecret"> 获取密保 </a-button>
        </a-form-item>
        <!--  这是第二部了 获取到了问题，然后展示，输入 传到后面 -->
        <div v-for="(item, index) in toBackInfo.questions" :key="index">
          <a-form-item v-if="questionVisible == true" label="问题">
            <a-input v-model="item.stem" readonly="true"></a-input>
          </a-form-item>
          <!-- 问题的回答 -->
          <a-form-item v-if="questionVisible == true" label="回答">
            <a-input
              v-model="item.answer"
              :placeholder="请输入密保回答"
            ></a-input>
          </a-form-item>
        </div>
        <!-- 新的密码 -->
        <a-form-item v-if="questionVisible == true" label="密码">
          <a-input
            v-model="toBackInfo.password"
            :placeholder="请输入新密码"
          ></a-input>
        </a-form-item>
        <!-- 提交的按钮 -->
        <a-space :size="16" direction="vertical">
          <a-button
            type="primary"
            html-type="submit"
            long
            :loading="loading"
            @click="questionFinalToBack"
          >
            重置密码
          </a-button>
        </a-space>
      </a-form>
    </div>
    <!-- 这里是根据手机号找回的输入框 -->
    <div v-if="phoneVisible == true">
      <a-form :model="toBackInfo">
        <a-form-item label="手机号">
          <a-input
            v-model="toBackInfo.phone"
            :placeholder="请输入手机号"
          ></a-input>
        </a-form-item>
        <a-form-item v-if="ucodeButtonVisible == true">
          <a-button type="primary" @click="acCodeButton"> 获取验证码 </a-button>
        </a-form-item>
        <!-- 输入新密码和验证码 -->
        <!-- 新的密码 -->
        <a-form-item v-if="phoneQuestionVisible == true" label="密码">
          <a-input
            v-model="toBackInfo.password"
            :placeholder="请输入新密码"
          ></a-input>
        </a-form-item>
        <a-form-item v-if="phoneQuestionVisible == true" label="验证码">
          <a-input
            v-model="toBackInfo.verificationCode"
            :placeholder="请输入验证码"
          ></a-input>
        </a-form-item>
        <!-- 提交的按钮 -->
        <a-space
          v-if="phoneQuestionVisible == true"
          :size="16"
          direction="vertical"
        >
          <a-button
            type="primary"
            html-type="submit"
            long
            :loading="loading"
            @click="phoneFinalToBack"
          >
            重置密码
          </a-button>
        </a-space>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import type { LoginData } from '@/api/user';
  import {
    useUsernameFindSecurityQuestion,
    useAnswerChangePassword,
    usePhoneObtainCode,
    usePhoneChangePassword,
  } from '@/api/user';

  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();

  // 找回密码的ts部分
  const choiceVisible = ref(true);
  // 密保找回的现实框
  const securityQuestionVisible = ref(false);
  // 密保找回用户名的框的是否
  const usernameButtonVisible = ref(false);
  // 密保找回 问题框是否显示
  const questionVisible = ref(false);
  // 手机号找回是否显示
  const phoneVisible = ref(false);
  // 发送验证码的按钮 （根据手机号找回）
  const ucodeButtonVisible = ref(false);
  // 手机号找回的密码和验证码部分
  const phoneQuestionVisible = ref(false);

  // 往后的数据
  const toBackInfo = ref({
    username: '',
    phone: '',
    password: '',
    verificationCode: '',
    questions: [
      {
        id: '',
        // 题干
        stem: '',
        answer: '',
      },
    ],
    answers: [
      {
        id: '',
        // 题干
        stem: '',
        // 回答
        answer: '',
      },
    ],
  });

  // 点击密保找回的按钮的方法
  const securityQuestionButton = () => {
    choiceVisible.value = false;
    securityQuestionVisible.value = true;
    usernameButtonVisible.value = true;
  };

  // 点击手机号找回的按钮的方法
  const phoneButton = () => {
    choiceVisible.value = false;
    phoneVisible.value = true;
    ucodeButtonVisible.value = true;
  };

  // 点击获取密保问题的按钮的方法
  const obtainSecret = async () => {
    const { data } = await useUsernameFindSecurityQuestion(toBackInfo);
    console.log('data');
    console.log(data);
    console.log('data');
    // 已经拿到数据了 赋值
    toBackInfo.value.questions = data;

    // 判断是否是正确的用户名

    // 得确定用户名存在才能变成false 隐藏起来
    usernameButtonVisible.value = false;
    // 然后再显示出来问题
    questionVisible.value = true;
  };

  // 在密保找回点击最终的按钮去修改密码
  const questionFinalToBack = async () => {
    // console.log('toBackInfo.value');
    // console.log(toBackInfo.value);
    // console.log('toBackInfo.value');
    toBackInfo.value.answers = toBackInfo.value.questions;
    const { data } = await useAnswerChangePassword(toBackInfo.value);
    // console.log(data);
    Message.success('密码重置成功');
  };

  // 点击发送验证码的按钮
  const acCodeButton = async () => {
    const { data } = await usePhoneObtainCode(toBackInfo.value);
    ucodeButtonVisible.value = false;
    phoneQuestionVisible.value = true;
  };

  // 点击验证码重置密码的按钮
  const phoneFinalToBack = async () => {
    const { data } = await usePhoneChangePassword(toBackInfo.value);
    Message.success('密码重置成功');
  };

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    username: 'admin', // 演示默认值
    password: 'admin', // demo default value
  });
  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
    phone: '',
    passwordConfirm: '',
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login(values as LoginData);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          name: (redirect as string) || 'Workplace',
          query: {
            ...othersQuery,
          },
        });
        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };
</script>

<style lang="less" scoped>
  .retrieve-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
